package baidu

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"net/url"
	"vrcm/src/vrcm/app/admin/models"
	dto "vrcm/src/vrcm/app/admin/service/dto/baidu"
	"vrcm/src/vrcm/common/service"
	ext "vrcm/src/vrcm/envconfig"
)

var client = http.Client{}

type BaiduService struct {
	service.Service
}

func (e *BaiduService) AuditSubmit(req *dto.AuditReq) (*dto.AuditRes, error) {
	res := dto.AuditRes{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.VrmServiceUrl + "/api/v1/baidu/submitAudit"
	Url, err := url.Parse(urlString)
	if err != nil {
		return &res, err
	}
	params.Set("permissionToken", "vsnb")
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("AuditSubmit", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["appid"] = req.AppId
	data["streamUrl"] = req.StreamUrl
	data["strategyId"] = req.StrategyId
	data["streamType"] = req.StreamType
	data["extId"] = req.ExtId
	data["startTime"] = req.StartTime
	data["endTime"] = req.EndTime
	data["streamName"] = req.StreamName
	data["streamDealInfo"] = req.StreamDealInfo
	data["subEvents"] = req.SubEvents
	data["noticeUrl"] = req.NoticeUrl
	data["region"] = req.Region
	data["detectType"] = req.DetectType
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Info(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	if err != nil {
		e.Log.Error("GetHttpSkip Request Error:", err)
		return nil, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Error("GetHttpSkip Response Error:", err)
		return nil, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Error("读取响应体失败 error:%s", err)
		return nil, err
	}
	e.Log.Info("AuditSubmit:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return nil, errors.New(result.Get("message").String())
	}

	res.Data.TaskId = result.Get("data").String()
	return &res, nil
}

func (e *BaiduService) AuditSubmit1(req *dto.AuditReq1) error {
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.VrmServiceUrl + "/api/v1/baidu/submitAudit"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("permissionToken", "vsnb")
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("AuditSubmit", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["source"] = req.Source
	data["preset"] = req.Preset
	data["notification"] = req.Notification
	data["description"] = req.Description
	data["notifyLevel"] = req.NotifyLevel
	data["thumbnailInterval"] = req.ThumbnailInterval
	data["audioInterval"] = req.AudioInterval
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Info(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Error("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Error("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Error("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Info("AuditSubmit:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}

	return nil
}

func (e *BaiduService) StopAudit(req *dto.StopAuditReq) error {
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.VrmServiceUrl + "/api/v1/baidu/stopAudit"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("permissionToken", "vsnb")
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("StopAudit", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["tenant_id"] = req.TenantId
	data["appid"] = req.AppId
	data["taskId"] = req.TaskId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Info(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Error("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Error("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Error("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Info("StopAudit:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}

	return nil
}

func (e *BaiduService) StopAudit1(req *dto.StopAuditReq) error {
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.VrmServiceUrl + "/api/v1/baidu/stopAudit"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("permissionToken", "vsnb")
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("StopAudit", urlPath)
	// 参数
	data := make(map[string]interface{})
	//data["source"] = req.Source
	//data["notification"] = "aa/bb"
	//data["taskId"] = req.TaskId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Info(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Error("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Error("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Error("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Info("StopAudit:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK && result.Get("code").Int() != 301057 {
		return errors.New(result.Get("message").String())
	}

	return nil
}

func (e *BaiduService) LongVideoAuditSubmit(req *dto.LongVideoAuditReq) (string, error) {
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.VrmServiceUrl + "/api/v1/baidu/longVideoAudit"
	Url, err := url.Parse(urlString)
	if err != nil {
		return "", err
	}
	params.Set("permissionToken", "vsnb")
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("LongVideoAuditSubmit", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["appid"] = req.AppId
	data["strategyId"] = req.StrategyId
	data["url"] = req.Url
	data["noticeUrl"] = req.NoticeUrl
	data["frequency"] = req.Frequency
	data["extId"] = req.ExtId
	data["subEvents"] = req.SubEvents
	data["detectType"] = req.DetectType
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Info(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	if err != nil {
		e.Log.Error("GetHttpSkip Request Error:", err)
		return "", err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Error("GetHttpSkip Response Error:", err)
		return "", err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Error("读取响应体失败 error:%s", err)
		return "", err
	}
	e.Log.Info("LongVideoAuditSubmit:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return "", errors.New(result.Get("message").String())
	}

	return result.Get("data").String(), nil
}
